<template>
  <div>
    <el-tag
      v-for="(tag, index) in value"
      :key="index"
      closable
      :disable-transitions="false"
      @close="removeTag(index)"
      style="margin-right: 8px;"
    >
      {{ tag }}
    </el-tag>

    <el-input
      v-if="inputVisible"
      v-model="inputValue"
      ref="inputRef"
      size="small"
      class="input-new-tag"
      @keyup.enter.native="addTag"
      @blur="addTag"
      style="width: 120px;"
      :disabled="disabled"
    />

    <el-button
      v-else
      class="button-new-tag"
      size="small"
      @click="showInput"
      :disabled="disabled"
    >
      + 添加标签
    </el-button>
  </div>
</template>

<script>
export default {
  name: 'TagInput',
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      inputVisible: false,
      inputValue: '',
    };
  },
  methods: {
    addTag() {
      const val = this.inputValue.trim();
      if (val && !this.value.includes(val)) {
        this.$emit('input', [...this.value, val]);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    removeTag(index) {
      const newTags = [...this.value];
      newTags.splice(index, 1);
      this.$emit('input', newTags);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.inputRef && this.$refs.inputRef.focus();
      });
    },
  },
};
</script>

<style scoped>
.input-new-tag {
  margin-right: 8px;
  vertical-align: middle;
}
.button-new-tag {
  margin-right: 8px;
  vertical-align: middle;
}
</style>
